﻿using System;
using System.Configuration;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using ChoViet.CMS.Components;
using ChoViet.CMS.Properties;
using ChoViet.CMS.ViewModels;
using ChoViet.Lib.Common;
using ChoViet.Lib.Helpers;
using ChoViet.Lib.Mail;
using ChoViet.Lib.Paging;
using ChoViet.Model;
using MyUtility;
using System.Web.UI.MobileControls;
namespace ChoViet.CMS.Controllers
{
    
    public class AdController : BaseController
    {        
        #region Site

        #region Site: HttpGet Index
        [HttpGet]
        public ActionResult Index(string demanNam, string cateName, string cityName, string adAtributeName, string adAtributeValue, int? cusTypeId, int? page)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            if (page == null) page = 1;
            var param = new AdIndexViewModel();
            try
            {
                param.Demand = !string.IsNullOrEmpty(demanNam) ? eDataContext.Demands.FirstOrDefault(e => e.ShortName == demanNam) : null;
                param.City = !string.IsNullOrEmpty(cityName) ? eDataContext.Cities.FirstOrDefault(e => e.ShortName == cityName) : null;
                param.Category = !string.IsNullOrEmpty(cateName) ? eDataContext.Categories.FirstOrDefault(e => e.ShortName == cateName) : null;
                param.AdAttribute = !string.IsNullOrEmpty(adAtributeName) ? eDataContext.AdAttributes.FirstOrDefault(e => e.ShortName == adAtributeName) : null;
                param.AdAttributeValue = !string.IsNullOrEmpty(adAtributeValue) ? eDataContext.AdAttributeValues.FirstOrDefault(e => e.ShortValue == adAtributeValue) : null;
                
                param.Keyword = "";
                param.CusType = cusTypeId != null ? cusTypeId.Value : 0;
                param.Ads = AdManager.GetListAd(param.Demand != null ? param.Demand.ID : 0, 0, param.City != null ? param.City.ID : 0, 0, param.CusType,
                param.Category != null ? param.Category.ID : 0, param.Keyword, true, true, "ModifyDate", "DESC", page.Value, Convert.ToInt32(Settings.Default.PageSizeListAd), 0);

                return View(param);
            }catch{
                eDataContext.Dispose();
                Messages.AddErrorMessage("Không load được dữ liệu!");
                return View(param);}
        }
        #endregion

        #region Site: HttpPost Index
        [HttpPost]
        public ActionResult Index(BoxSearchAdModel frmdata)
        {
            var param = new AdIndexViewModel();
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {

                param.Ads = AdManager.GetListAd(frmdata.CurDemandID != null ? frmdata.CurDemandID : 0, frmdata.CurCountryID != null ? frmdata.CurCountryID : 0, frmdata.CurAreaID != null ? frmdata.CurAreaID : 0, frmdata.CurCityID != null ? frmdata.CurCityID : 0,
                frmdata.CurDistrictID != null ? frmdata.CurDistrictID : 0, frmdata.CurCusTypeID, frmdata.CurCategoryID != null ? frmdata.CurCategoryID : 0, frmdata.Keyword != null ? frmdata.Keyword : "", true, true, "ModifyDate", "DESC", 1, Convert.ToInt32(Settings.Default.PageSizeListAd), 0);
                param.Demand = frmdata.CurDemandID != null ? eDataContext.Demands.FirstOrDefault(e => e.ID == frmdata.CurDemandID) : null;
                param.Country = frmdata.CurCountryID != null ? eDataContext.Countries.FirstOrDefault(e => e.ID == frmdata.CurCountryID) : null;
                param.Area = frmdata.CurAreaID != null ? eDataContext.Areas.FirstOrDefault(e => e.ID == frmdata.CurAreaID) : null;
                param.City = frmdata.CurCityID != null ? eDataContext.Cities.FirstOrDefault(e => e.ID == frmdata.CurCityID) : null;
                param.District = frmdata.CurDistrictID != null ? eDataContext.Districts.FirstOrDefault(e => e.ID == frmdata.CurDistrictID) : null;
                param.CusType = frmdata.CurCusTypeID;
                param.Category = frmdata.CurCategoryID != null ? eDataContext.Categories.FirstOrDefault(e => e.ID == frmdata.CurCategoryID) : null;
                
                return View(param);
            }
            catch { eDataContext.Dispose();  return View(param); }
        }
        #endregion

        public ActionResult Create()
        {
            var param = new AdCreateViewModel();
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                param.CusTypes = Utils.StringToDictionary(Settings.Default.CusTypes.ToString(), ",");
                param.Countries = eDataContext.Countries.ToList();
                param.Cities = eDataContext.Cities.ToList();
                param.Districts = eDataContext.Districts.Where(e => e.City.ID == 13).ToList();
                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                param.CostTypes = eDataContext.CostTypes.ToList();
                param.Demands = eDataContext.Demands.ToList();
                param.CostTypes = eDataContext.CostTypes.ToList();
                var temp = new BaseAuthentication();
                param.CurrentUser = temp.CurrentUser;
                return View(param);
            }
            catch { eDataContext.Dispose(); ViewData["MessageInfo"] = "Tổng hợp dữ liệu ban đầu gặp sự cố!";
            Messages.AddErrorMessage("Tổng hợp dữ liệu chưa đầy đủ");
                return View(); }
        }

        #region Site: HttpPost Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(AdCreateViewModel rdata)
        {
            //Test captchar code
                
                    ChoVietDataContext eDataContext = new ChoVietDataContext();
                    if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                    eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                    bool isPub = Boolean.Parse(Settings.Default.AD_IsEnablePublish.ToString());
                    var basecaptchar = HttpContext.Session["captchastring"].ToString();
                    if (rdata.CaptchaCode == basecaptchar)
                    {
                    try
                    {
                        UpdateModel(rdata);
                        var temp = new BaseAuthentication();
                        if (temp.CurrentUser != null) rdata.Ad.UserID = temp.CurrentUser.ID;
                        rdata.Ad.Content = Request["AdContent"];
                        rdata.Ad.CreatedDate = DateTime.Now;
                        rdata.Ad.ModifyDate = rdata.Ad.CreatedDate;
                        rdata.Ad.ActiveYN = true;
                        rdata.Ad.AreaID = eDataContext.Cities.Where(e => e.ID == rdata.Ad.CityID).Select(e => e.AreaID).FirstOrDefault();
                        rdata.Ad.ViewNumber = Utils.Random2Number(2, 10);

                        if (isPub)
                        {
                            rdata.Ad.PublishYN = true;
                            rdata.Ad.ViewNumber = 0;
                        }
                        eDataContext.Ads.InsertOnSubmit(rdata.Ad);
                        eDataContext.SubmitChanges();
                        //Image display
                        HttpPostedFileBase fileImage = Request.Files["AdImage"];
                        if (fileImage != null && fileImage.ContentLength > 0)
                        {
                            var gallery = new Gallery();
                            gallery.AdID = rdata.Ad.ID;
                            var pathreduce = Utils.ReduceImageSize("\\" + Settings.Default.AdImageDescriptionPath + rdata.Ad.ID.ToString() + "_" + fileImage.FileName, Settings.Default.SiteRootPath, Convert.ToInt32(Settings.Default.RedureSizePercent), fileImage);
                            gallery.Path = pathreduce;

                            var img = Utils.CreateThumbnail(Settings.Default.AdminRootPath + pathreduce.Replace('/', '\\'), Convert.ToInt32(Settings.Default.GenThumbAdWidth), Convert.ToInt32(Settings.Default.GenThumbAdHeight));
                            rdata.Ad.Image = Utils.SaveThumbnail(img, Convert.ToInt32(Settings.Default.GenThumbAdWidth), Convert.ToInt32(Settings.Default.GenThumbAdWidth), Settings.Default.AdImageAvatarPath + rdata.Ad.ID + "_" + fileImage.FileName, Settings.Default.SiteRootPath);
                            eDataContext.Galleries.InsertOnSubmit(gallery);
                            eDataContext.SubmitChanges();
                        }
                        // Upload image descriptions - gallery
                        foreach (string inputTagName in Request.Files)
                        {
                            HttpPostedFileBase file = Request.Files[inputTagName];
                            if (file.ContentLength > 0 && inputTagName != "AdImage")
                            {
                                var r = new Gallery();
                                r.AdID = rdata.Ad.ID;
                                r.CreatedDate = DateTime.Now;
                                r.Path = Utils.ReduceImageSize("\\" + Settings.Default.AdImageDescriptionPath + rdata.Ad.ID.ToString() + "_" + file.FileName, Settings.Default.SiteRootPath, Convert.ToInt32(Settings.Default.RedureSizePercent), file);
                                eDataContext.Galleries.InsertOnSubmit(r);
                                eDataContext.SubmitChanges();
                            }
                        }
                        // Xử lý tags then tag automatic
                        //var listTags = eDataContext.Tags.ToList();
                        ////var listAdTagMaps = new List
                        //List<AdTagMap> adTagMaps = new List<AdTagMap>();
                        //var title = rdata.Ad.Title.Trim().ToLower();
                        //foreach (var item in listTags)
                        //{
                        //    if (title.Contains(item.Name.ToLower()))
                        //    {
                        //        AdTagMap atm = new AdTagMap() { AdID = rdata.Ad.ID, TagID = item.ID };
                        //        adTagMaps.Add(atm);
                        //    }
                        //}
                        //if (adTagMaps.Count() > 0) eDataContext.AdTagMaps.InsertAllOnSubmit(adTagMaps);
                        eDataContext.Transaction.Commit();

                    }
                    catch (Exception exp)
                    {
                        eDataContext.Transaction.Rollback();
                        eDataContext.Dispose();
                        MyLogfile.WriteLogData("Error", exp.ToString());
                        Messages.AddErrorMessage("Đăng tin rao vặt không thành công. Bạn vui lòng xem lại dữ liệu! Hoặc liên hệ với hỗ trợ viên để được trợ giúp");
                        return RedirectToAction("Create");
                    }
                    Messages.ClearAllMessage();
                    Messages.AddFlashMessage("Thông báo: Bạn đã đăng tin rao thành công!");
                    if (isPub)
                    {
                        Messages.AddFlashMessage("Tin rao '" + rdata.Ad.Title + "' của bạn đã được đăng trên website");
                    }
                    else
                    {
                        Messages.AddFlashMessage("Tin rao '" + rdata.Ad.Title + "' của bạn sẽ được duyệt chậm nhất trong vòng 6h");
                        Messages.AddFlashMessage("Chúng tôi sẽ gửi email thông báo cho bạn ngay sau khi tin rao của bạn được duyệt");
                    }
                    Messages.AddFlashMessage("Cám ơn bạn đã tin tưởng và đăng tin trên hệ thống của chúng tôi!");
                    Messages.AddFlashMessage("Thân ái... Chợ102.vn");
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    Messages.AddErrorMessage("Đăng tin rao vặt không thành công. Bạn vui lòng xem lại dữ liệu! Hoặc liên hệ với hỗ trợ viên để được trợ giúp");
                    UpdateModel(rdata);
                    rdata.CusTypes = Utils.StringToDictionary(Settings.Default.CusTypes.ToString(), ",");
                    rdata.Countries = eDataContext.Countries.ToList();
                    rdata.Cities = eDataContext.Cities.ToList();
                    rdata.Districts = eDataContext.Districts.Where(e => e.City.ID == 13).ToList();
                    rdata.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                    rdata.CostTypes = eDataContext.CostTypes.ToList();
                    rdata.Demands = eDataContext.Demands.ToList();
                    rdata.CostTypes = eDataContext.CostTypes.ToList();
                    rdata.CaptchaCode = "";
                    var temp = new BaseAuthentication();
                    rdata.CurrentUser = temp.CurrentUser;
                    return View(rdata);
                }
        }
        #endregion

        #region Site: Details
        public ActionResult Details(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new AdDetailsViewModel();
            try
            {
                param.Demand = new Demand();
                var currentPageComment = Request["page"] != null ? Convert.ToInt32(Request["page"]) : 0;
                param.Ad = eDataContext.Ads.FirstOrDefault(e => e.ID == id);
                param.Ad.ViewNumber = string.IsNullOrEmpty(param.Ad.ViewNumber.ToString()) ? 1 : param.Ad.ViewNumber + 1;
                Category cate = new Category();
                cate = eDataContext.Categories.FirstOrDefault(e => e.ID == param.Ad.CatID);
                cate.nView = string.IsNullOrEmpty(cate.nView.ToString()) ? 1 : cate.nView + 1;
                param.AdAttribute = new AdAttribute();
                param.AdAttributeValue = new AdAttributeValue();
                param.AdVIPs = eDataContext.Ads.Where(e => e.PublishYN == true && e.Status >= 2).OrderByDescending(e => e.ModifyDate).Take(6).ToList();
                param.Comments = eDataContext.Comments.Where(e => e.AdID == id || e.ParentComment.ID == id).ToPagedList(currentPageComment, Convert.ToInt32(Settings.Default.PageSizeListComment.ToString()));
                param.Galleries = eDataContext.Galleries.Where(e => e.AdID == id).ToList();
                param.TotalAdSameUser = eDataContext.Ads.Count(e => param.Ad.UserID != null ? e.UserID == param.Ad.UserID && e.ID != param.Ad.ID : false);
                param.Tags = AdManager.GetTagsByAdId(param.Ad.ID);
                return View(param);
            }
            catch
            {
                eDataContext.Dispose();
                Messages.ClearAllMessage();
                Messages.AddFlashMessage("Tin rao này đã hết hạn đăng tin hoặc tin rao đã được yêu cầu xóa!");
                return View(param);
            }
            finally {
                eDataContext.SubmitChanges();
            }
        }
        #endregion

        #region Site: BoxSearchAd
        [ChildActionOnly]
        public ActionResult BoxSearchAd(int? demandId,int? countryId, int? areaId, int? cityId, int? districtId, int? custypeId, int? cateId, string keyword)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new BoxSearchAdModel();
            try
            {
            if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
            param.Countries = eDataContext.Countries.ToList();
            param.Areas = eDataContext.Areas.Where(e => (countryId != null && countryId.Value > 0 ? e.CountryID == countryId.Value : true)).ToList();
            param.Demands = eDataContext.Demands.ToList();
            param.Cities = eDataContext.Cities.Where(e => (areaId.Value > 0 ? e.AreaID == areaId.Value : true)).ToList();
            param.Districts = eDataContext.Districts.Where(e => cityId.Value > 0 ? e.CityID == cityId.Value : false).ToList();
            param.CusTypes = Utils.StringToDictionary(Settings.Default.CusTypes.ToString(), ",");
            param.Categories = CategoryManager.BuiltCombobox(cateId.Value);
            param.Keyword = keyword;
            param.CurDemandID = demandId.Value;
            param.CurCountryID = countryId.Value;
            param.CurAreaID = areaId.Value;
            param.CurCityID = cityId.Value;
            param.CurDistrictID = districtId.Value;
            param.CurCusTypeID = custypeId.Value;
            param.CurCategoryID = cateId.Value;
            return View(param);
            }
            catch
            {
                eDataContext.Dispose();
                return View(param);
            }
        }
        #endregion

        #region Site: BoxNewAds
        [ChildActionOnly]
        public ActionResult BoxNewAds(int cateId, int custypeId, int boxsize)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new BoxNewAdsViewModel();
            try
            {
                param.Ads = eDataContext.Ads.Where(e => e.PublishYN == true && e.Status >= 2 && (cateId > 0 ? e.CatID == cateId : true) && (custypeId > 0 ? e.CusTypeID == custypeId : true)).OrderByDescending(e => e.ModifyDate).Take(boxsize).ToList();
                return View(param);
            }
            catch { eDataContext.Dispose(); return View(param); }
        }
        #endregion

        #region Site: Tabs
        [ChildActionOnly]
        public ActionResult Tabs(int cateId,int custypeId, int count)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new AdTabsViewModel();
            try
            {
                param.Ads = eDataContext.Ads.Where(e => (e.PublishYN == true) && (e.CatID == cateId || e.Category.ParentID == cateId) && (custypeId > 0 ? e.CusTypeID == custypeId : true))
                                                .OrderByDescending(e => e.ModifyDate).Take(count).ToList();
                param.CurrentCusType = custypeId;
                param.Count = count;
                param.Category = eDataContext.Categories.FirstOrDefault(e => e.ID == cateId);
                return View(param);
            }
            catch { eDataContext.Dispose(); return View(param); }
        }
        #endregion

        #region Site: BoxHotAds
        [ChildActionOnly]
        public ActionResult BoxHotAds(int cateId, int boxsize)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new BoxHotAdsViewModel();
            try
            {
                param.Ads = eDataContext.Ads.Where(e => (cateId > 0 ? e.CatID == cateId : true) &&
                            e.PublishYN == true && e.Status == 1).OrderByDescending(e => e.ModifyDate).Take(boxsize).ToList();
                return View(param);
            }
            catch { eDataContext.Dispose(); return View(param); }
        }
        #endregion

        #region Site: ThenSubMenu
        [ChildActionOnly]
        public ActionResult SubMenu(Demand demand, Category category, City city, Country country)
        {
            var param = new SubMenuViewModel();
            param.Demand = demand;
            param.Category = category;
            param.Country = country;
            param.City = city;
            return View(param);
        }
        #endregion

        #region Site: loadAdByUserId
        public ActionResult loadAdByUserId(int id,int adId, int type)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new ListAdByUserIdViewModel();
            try
            {
                param.Ads = eDataContext.Ads.Where(e => e.ActiveYN == true && e.PublishYN == true && e.UserID == id && e.ID != adId).ToPagedList(type, 20);
                return View(param);
            }
            catch { eDataContext.Dispose(); return View(param); }
        }

        #endregion

        #region Site: LoadAdTheSameCate
        public ActionResult LoadAdTheSameCate(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new LoadAdTheSameCateViewModel();
            try
            {
                param.Ads = eDataContext.Ads.Where(e => e.ActiveYN == true && e.PublishYN == true && e.CatID == id).OrderByDescending(e => e.ModifyDate).Take(20).ToList();
                return View(param);
            }
            catch { eDataContext.Dispose(); return View(param); }
        }
        #endregion

        #region Site: LoadListAdByTabs
        public ActionResult LoadListAdByTabs(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new LoadListAdByTabsViewModel();
            var custypeId = Request["CustypeID"] != null ? Convert.ToInt32(Request["CustypeID"]) : 0;
            var count = Request["Count"] != null ? Convert.ToInt32(Request["Count"]) : 8;
            try
            {
                param.Ads = eDataContext.Ads.Where(e => (e.PublishYN == true) && (e.CatID == id || e.Category.ParentID == id) && (custypeId > 0 ? e.CusTypeID == custypeId : true))
                            .OrderByDescending(e => e.ModifyDate).Take(count).ToList();
                return View(param);
            }
            catch { eDataContext.Dispose(); return View(param); }
        }
        #endregion

        #region Site: AdPromotion
        [ChildActionOnly]
        public ActionResult AdPromotion(int count)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            BoxPromotionAdViewModel model = new BoxPromotionAdViewModel();
            try
            {
                model.Ads = eDataContext.Ads.Where(e => e.ActiveYN == true).Take(count).OrderByDescending(e => e.ModifyDate).ToList();
                model.PathTemplateContent = "~\\Views\\Ad\\PromotionAd.html";
                model.PathTemplateTitle = "~\\Views\\Ad\\ListPromotionAd.html";
                return View(model);
            }
            catch (Exception ex)
            {
                return View(model);
            }
        }
        #endregion


        #region Site: LoadAdByCondition
        public ActionResult LoadAdByCondition(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            LoadAdByConditionViewModle model = new LoadAdByConditionViewModle();
            string nameAction = Request["nameAction"].ToString();
            try
            {
                if (nameAction == "contentin")
                { 
                    
                }
                else if (nameAction == "tabconten2")
                {
                    model.Ads = eDataContext.Ads.Where(e => e.ActiveYN == true && e.PublishYN == true).OrderByDescending(e => e.ModifyDate).Take(id).ToList();
                }
                else 
                {
                    model.Ads = eDataContext.Sp_Ad_Select_HighestViewNumber_PerWeek(id, DateTime.Now.AddDays(-7), DateTime.Now).ToList();
                }
                if (model.Ads != null && model.Ads.Count() > 0)
                {
                    return View(model);
                }
                else
                    return null;
            }
            catch
            {
                return null;
            }
        }

        #endregion

        #endregion

        #region CMS

        #region HttpGet IndexCms
        [RoleHelper(Roles = RoleSystem.Product)]
        public ActionResult IndexCms(int? page)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new AdIndexCMSViewModel();
            try
            {
                if (page == null) page = 1;
                string order = UserState.getUserStateFromRequest("Ad.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("Ad.orderDir", "orderDir", "desc").ToString();
                param.CurentCateId = Convert.ToInt32(UserState.getUserStateFromRequest("Ad.CatID", "CatID", 0));
                param.CurentAreaId = Convert.ToInt32(UserState.getUserStateFromRequest("Ad.AreaID", "AreaID", 0));
                param.CurentCityId = Convert.ToInt32(UserState.getUserStateFromRequest("Ad.CityID", "CityID", 0));
                param.CurentDistrictId = Convert.ToInt32(UserState.getUserStateFromRequest("Ad.DistrictID", "DistrictID", 0));
                param.CurentAdFormId = Convert.ToInt32(UserState.getUserStateFromRequest("Ad.AdFormId", "AdFormId", 0));
                param.CurentPubStatusId = Convert.ToInt32(UserState.getUserStateFromRequest("Ad.PubStatusId", "PubStatusId", 0));
                param.CurentHOTId = Convert.ToInt32(UserState.getUserStateFromRequest("Ad.HotId", "HotId", 0));
                param.AdForms = Utils.StringToDictionary(Settings.Default.AdForms, ",");
                param.PubStatus = Utils.StringToDictionary(Settings.Default.PubStatus, ",");
                param.HOTs = Utils.StringToDictionary(Settings.Default.HotStatus, ",");

                param.Keyword = UserState.getUserStateFromRequest("Ad.Keyword", "Keyword", "").ToString();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("article.pageSize", "PageSize", Settings.Default.PageSize).ToString());
                param.Ads = eDataContext.Ads
                    .Where(a => (param.CurentCateId > 0 ? (a.Category.ParentCategory.ID == param.CurentCateId || a.CatID == param.CurentCateId) : true))
                    .Where(a => param.CurentAreaId > 0 ? a.AreaID == param.CurentAreaId || a.City.AreaID == param.CurentAreaId : true)
                    .Where(a => param.CurentCityId > 0 ? a.CityID == param.CurentCityId : true)
                    .Where(a => param.CurentDistrictId > 0 ? a.DistrictID == param.CurentDistrictId : true)
                    .Where(a => param.CurentAdFormId!= null && param.CurentAdFormId == 1 ? a.SourceUrl == null : true)
                    .Where(a => param.CurentAdFormId != null && param.CurentAdFormId == 2 ? a.SourceUrl != null : true)
                    .Where(a => param.CurentPubStatusId != null && param.CurentPubStatusId == 1 ? a.PublishYN == true : true)
                    .Where(a => param.CurentPubStatusId != null && param.CurentPubStatusId == 2 ? (a.PublishYN == false || a.PublishYN == null) : true)
                    .Where(a => param.CurentHOTId != null && param.CurentHOTId == 1 ? a.Status == 1 : true)
                    .Where(a => param.CurentHOTId != null && param.CurentHOTId == 2 ? (a.Status == 0 || a.Status == null) : true)
                    .Where(a => (string.IsNullOrEmpty(param.Keyword) ? true : (a.Title.ToLower().Contains(param.Keyword.ToLower()) || a.Content.Contains(param.Keyword) || a.MobileContact.Contains(param.Keyword) || a.ID.ToString() == param.Keyword || a.PhoneContact.Contains(param.Keyword) || a.EmailContact.Contains(param.Keyword))))
                    .OrderBy(string.Format("{0} {1}", order, orderDir))
                    .ToPagedList(page.Value - 1, pageSize);

                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(param.CurentCateId);
                param.Areas = eDataContext.Areas.ToList();
                param.Cities = eDataContext.Cities.Where(e => e.AreaID == param.CurentAreaId).ToList();
                param.Districts = eDataContext.Districts.Where(e => e.CityID == param.CurentCityId).ToList();


                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;
                return View(param);
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion

        #region HttpGet CreateCms
        [RoleHelper(Roles = RoleSystem.Product)]
        public ActionResult CreateCms()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new AdEditCMSViewModel();
            try
            {
                param.Cities = eDataContext.Cities.ToList();
                param.Districts = eDataContext.Districts.Where(e => e.City.ID == 13).ToList();
                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                param.CostTypes = eDataContext.CostTypes.ToList();
                param.Demands = eDataContext.Demands.ToList();
                param.CostTypes = eDataContext.CostTypes.ToList();
                return View(param);
            }
            catch { eDataContext.Dispose(); ViewData["MessageInfo"] = "Tổng hợp dữ liệu ban đầu gặp sự cố!"; return View(); }
        }
        #endregion

        #region HttpPost CreateCms
        [ValidateInput(false)][HttpPost] [RoleHelper(Roles = RoleSystem.Product)]
        public ActionResult CreateCms(AdEditCMSViewModel rdata)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
            eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
            try
            {
                UpdateModel(rdata);
                rdata.Ad.CreatedBy = UserManager.GetUserId();
                rdata.Ad.CreatedDate = DateTime.Now;
                rdata.Ad.ViewNumber = Utils.Random2Number(2,10);
                eDataContext.Ads.InsertOnSubmit(rdata.Ad);
                eDataContext.SubmitChanges();
                //Image display
                HttpPostedFileBase fileImage = Request.Files["AdImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    rdata.Ad.Image = Uploads.UploadFile(fileImage, Settings.Default.AdImageAvatarPath,Settings.Default.SiteRootPath,rdata.Ad.ID.ToString());
                }
               

                // Upload image descriptions - gallery
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0 && inputTagName != "AdImage")
                    {
                        var r = new Gallery();
                        r.AdID = rdata.Ad.ID;
                        r.CreatedBy = UserManager.GetUserId();
                        r.CreatedDate = DateTime.Now;
                        r.Path = Uploads.UploadFile(file, Settings.Default.AdImageDescriptionPath,Settings.Default.SiteRootPath, rdata.Ad.ID.ToString());
                        eDataContext.Galleries.InsertOnSubmit(r);
                        eDataContext.SubmitChanges();
                    }
                }
                // Xử lý tags
                eDataContext.Transaction.Commit();
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
            Messages.AddFlashMessage("Đăng tin rao vặt thành công!");
            return RedirectToAction("IndexCms");
        }
        #endregion

        [HttpGet]
        [RoleHelper(Roles = RoleSystem.Product)]
        public ActionResult EditCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new AdEditCMSViewModel();
            try
            {
                param.Ad = eDataContext.Ads.FirstOrDefault(e => e.ID == id);
                param.Cities = eDataContext.Cities.ToList();
                param.Districts = eDataContext.Districts.Where(e => e.City.ID == 13).ToList();
                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                param.CostTypes = eDataContext.CostTypes.ToList();
                param.Demands = eDataContext.Demands.ToList();
                param.CostTypes = eDataContext.CostTypes.ToList();
                param.Galleries = eDataContext.Galleries.Where(e => e.AdID == id).ToList();
                param.MailStatus = Utils.StringToDictionary(Settings.Default.MailStatus, ",");
                return View(param);
            }
            catch (Exception)
            {
                ViewData["MessageInfo"] = "Tin rao này không tồn tại trong hệ thống";
                Messages.AddFlashMessage("Tin rao này không tồn tại trong hệ thống");
                return View();
            }
        }
        [HttpPost]
        [ValidateInput(false)]
        [RoleHelper(Roles = RoleSystem.Product)]
        public ActionResult EditCms(int id , AdEditCMSViewModel fromdata)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                fromdata.Ad = eDataContext.Ads.FirstOrDefault(e => e.ID == id);
                UpdateModel(fromdata);
                
                fromdata.Ad.ModifyBy = UserManager.GetUserId();
                fromdata.Ad.CreatedDate = DateTime.Now;
                fromdata.Ad.ModifyDate = DateTime.Now;
                //Image display
                HttpPostedFileBase fileImage = Request.Files["AdImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    //Delete old avatar
                    if (!string.IsNullOrEmpty(fromdata.Ad.Image)) Uploads.DeleteFile(System.AppDomain.CurrentDomain.BaseDirectory + fromdata.Ad.Image.Replace('/', '\\'));
                    var gallery = new Gallery();
                    gallery.AdID = fromdata.Ad.ID;
                    gallery.Path = Utils.ReduceImageSize("\\" + Settings.Default.AdImageDescriptionPath + fromdata.Ad.ID.ToString() + "_" + fileImage.FileName,Settings.Default.SiteRootPath, Convert.ToInt32(Settings.Default.RedureSizePercent), fileImage);
                    // resize image to avatar image;
                    var img = Utils.CreateThumbnail(Settings.Default.AdminRootPath + gallery.Path.Replace('/', '\\'), Convert.ToInt32(Settings.Default.GenThumbAdWidth), Convert.ToInt32(Settings.Default.GenThumbAdHeight));
                    fromdata.Ad.Image = Utils.SaveThumbnail(img, Convert.ToInt32(Settings.Default.GenThumbAdWidth), Convert.ToInt32(Settings.Default.GenThumbAdWidth), Settings.Default.AdImageAvatarPath + fromdata.Ad.ID + "_" + fileImage.FileName,Settings.Default.SiteRootPath);
                    eDataContext.Galleries.InsertOnSubmit(gallery);
                    eDataContext.SubmitChanges();
                }
                // Upload image descriptions - gallery
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0 && inputTagName != "AdImage")
                    {
                        var r = new Gallery();
                        r.AdID = fromdata.Ad.ID;
                        r.CreatedDate = DateTime.Now;
                        r.Path = Utils.ReduceImageSize("\\" + Settings.Default.AdImageDescriptionPath + fromdata.Ad.ID.ToString() + "_" + file.FileName,Settings.Default.SiteRootPath, Convert.ToInt32(Settings.Default.RedureSizePercent), file);
                        eDataContext.Galleries.InsertOnSubmit(r);
                        eDataContext.SubmitChanges();
                    }
                }
                eDataContext.SubmitChanges();
                Messages.AddFlashMessage("Sửa tin rao thành công!");
                var mailStatusId = Request["MailStatusId"] != null && !string.IsNullOrEmpty(Request["MailStatusId"]) ? Convert.ToInt32(Request["MailStatusId"]) : 0;
                // Gửi mail thông báo
                if (!string.IsNullOrEmpty(fromdata.Ad.EmailContact) && mailStatusId > 0)
                {
                    string subject = "";
                    string fromMail = ConfigurationManager.AppSettings["DefaultFromMail"];
                    try
                    {
                        var links = "";
                        var body = "";
                        if (mailStatusId == 1)
                        {
                            links = LinkUtils.domain+AdHelpers.AdDetailRoute(fromdata.Ad);
                            subject = "Chợ102.vn - Tin quảng cáo đã được chấp nhận:''" + fromdata.Ad.Title + "''";
                            body = string.Format(MailContent.PubAdBodyMail, fromdata.Ad.NameContact, links, links, fromdata.Ad.NameContact, fromdata.Ad.EmailContact,fromdata.Ad.MobileContact, fromdata.Ad.Title, fromdata.Ad.Content);
                        }
                        else {
                            subject = "Chợ102.vn - Chúng tôi rất tiếc tin quảng cáo của bạn không được chấp nhận:''" + fromdata.Ad.Title + "''";
                            body = string.Format(MailContent.NotPubAdBodyMail, fromdata.Ad.NameContact, fromdata.Ad.NameContact, fromdata.Ad.EmailContact,fromdata.Ad.MobileContact, fromdata.Ad.Title, fromdata.Ad.Content);
                        }
                        SmtpMailer.sendMail(fromdata.Ad.EmailContact, fromMail, subject, body);
                        Messages.AddFlashMessage("Đã gửi email thông báo tới cho người đăng tin");
                        fromdata.Ad.SendEmailYN = true;
                        eDataContext.SubmitChanges();
                    }
                    catch (Exception)
                    {
                        Messages.AddFlashMessage("Gửi email thông báo tới cho khách hàng gặp lỗi!");
                        throw new IndexOutOfRangeException();
                    }
                }
                return RedirectToAction("IndexCms");
            }
            catch (Exception  exp)
            {
                ViewData["MessageInfo"] = exp.Message;
                return View();    
            }
            
        }

        public ActionResult DetailsCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new AdEditCMSViewModel();
            try
            {
                param.Ad = eDataContext.Ads.FirstOrDefault(e => e.ID == id);
                param.Galleries = eDataContext.Galleries.Where(e => e.AdID == id).ToList();
                return View(param);
            }
            catch (Exception exp)
            {
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }

        public ActionResult UpdateModifileDate()
        {
            int page = 1;
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            
            
                for (int x = 1; x < 4900; x++)
                {
                    IPagedList<Ad> Ads = eDataContext.Ads.Where(e => e.ModifyDate == null).ToPagedList(page - 1, 20);
                    if (Ads.Count() > 0)
                    {
                        foreach (var item in Ads)
                        {
                            item.ModifyDate = item.CreatedDate;
                        }
                        eDataContext.SubmitChanges();
                    }
                }
                return RedirectToAction("IndexCMS", "Home");
            
        }
        #endregion

        public JsonResult DeleteImg(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var item = eDataContext.Galleries.Where(e => e.ID == id).FirstOrDefault();
                //var fullpath = System.AppDomain.CurrentDomain.BaseDirectory + item.Path.Replace('/', '\\');
                var fullpath = Settings.Default.AdminRootPath + item.Path.Replace('/', '\\');
                Uploads.DeleteFile(fullpath);
                eDataContext.Galleries.DeleteOnSubmit(item);
                eDataContext.SubmitChanges();
                return Json(true);
            }
            catch (Exception exp)
            {
                Response.Write(exp.Message);
                return Json(false);
            }
        }

        public JsonResult RefreshAd(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var item = eDataContext.Ads.Where(e => e.ID == id).FirstOrDefault();
                if (item != null)
                {
                    item.ModifyDate = DateTime.Now;
                    item.RefreshNumber = string.IsNullOrEmpty(item.RefreshNumber.ToString()) ? 1 : item.RefreshNumber + 1;
                }
                eDataContext.SubmitChanges();
                return Json(true);
            }
            catch (Exception exp)
            {
                Response.Write(exp.Message);
                return Json(false);
            }
        }

        public JsonResult DeleteListAd(string listId)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            //var listId = Request["ListID"];
            if (!string.IsNullOrEmpty(listId))
            {
                var lstId = listId.Split(',');
                // Delete Ad
                foreach (var itemId in lstId)
                {
                    if (!string.IsNullOrEmpty(itemId))
                    {
                        var id = Convert.ToInt32(itemId);
                        var curentAd = eDataContext.Ads.FirstOrDefault(e => e.ID == id);
                        if (curentAd != null)
                        {
                            // Delete avatar ad imge
                            if (!string.IsNullOrEmpty(curentAd.Image))
                            {
                                var path = Settings.Default.AdminRootPath + curentAd.Image.Replace('/', '\\');
                                Uploads.DeleteFile(path);
                            }

                            // Delete description imge
                            var lst = eDataContext.Galleries.Where(e => e.AdID == id).ToList();
                            if (lst != null && lst.Count() > 0)
                            {
                                foreach (var item in lst)
                                {
                                    var itempath = Settings.Default.AdminRootPath + item.Path.Replace('/', '\\');
                                    Uploads.DeleteFile(itempath);
                                }
                                eDataContext.Galleries.DeleteAllOnSubmit(lst);
                            }
                            // Delete AdTagMap
                            var tagmaps = eDataContext.AdTagMaps.Where(e => e.AdID == id).ToList();
                            if (tagmaps != null && tagmaps.Count() > 0) { eDataContext.AdTagMaps.DeleteAllOnSubmit(tagmaps); }
                            // Delete all Comment
                            var comments = eDataContext.Comments.Where(e => e.AdID == id).ToList();
                            if (comments != null && comments.Count() > 0) { eDataContext.Comments.DeleteAllOnSubmit(comments); }
                            //Delete adAdtributema
                            var adadtributemap = eDataContext.AdAttributeMaps.Where(e => e.AdID == id).ToList();
                            if (adadtributemap != null && adadtributemap.Count() > 0)
                            {
                                eDataContext.AdAttributeMaps.DeleteAllOnSubmit(adadtributemap);
                            }
                            // Delete FeedBack
                            var feedback = eDataContext.Feedbacks.Where(e => e.AdID == id).ToList();
                            if (feedback != null && feedback.Count() > 0) eDataContext.Feedbacks.DeleteAllOnSubmit(feedback);
                            eDataContext.SubmitChanges();
                            eDataContext.Ads.DeleteOnSubmit(curentAd);
                            eDataContext.SubmitChanges();
                        }
                    }
                }
                return Json(true);
            }
            return Json(false);
        }

    }
}
